<template>
  <div class="index_body">
    <div class="scroll-list-wrap" :click="true" :style="{height:getWindowHeight+'px'}">
        <cube-scroll
          ref="scrolls"
          :data="store_list"
          :options="options"
          @pulling-up="onPullingUp">
              <div class="head" :style="index_bg">
                  <router-link tag="div" :to="{ name: 'SelectAddress'}" class="address">
                      <h3 class="address_txt"><i class="dinwei_icon" :style="dinwei_icon"></i>{{$store.state.address_status}}<i class="down_icon" :style="down_icon"></i></h3>
                  </router-link>
                  <div class="nav">
                      <cube-scroll ref="scroll" :data="cate_list" :options="options_cate" direction="horizontal" class="horizontal-scroll-list-wrap">
                          <ul>
                              <li v-for="(item,index) in cate_list" :class="{action : item.id == cate_list_action}" @click="btn_select_cate(index)">{{item.name}}</li>
                          </ul>
                      </cube-scroll>
                  </div>
                  <div class="search">
                      <div class="search_input">
                          <!-- <p v-show="!is_search_input" @click="search_txt()"><i class="search_icon" :style="search_icon"></i>搜索商家名称获得优惠券</p> -->
                          <cube-input
                              v-model="search_input.value"
                              :placeholder="search_input.placeholder"
                              :type="search_input.type"
                              :maxlength="search_input.maxlength"
                              :readonly="search_input.readonly"
                              :disabled="search_input.disabled"
                              :autofocus="search_input.autofocus"
                              :autocomplete="search_input.autocomplete"
                              :eye="search_input.eye"
                              :clearable="search_input.clearable"
                              class="search_input"
                              v-on:input="search_key"
                            ></cube-input>
                      </div>
                  </div>
                  <div class="head_bg">
                      <div class="bg_top">

                      </div>
                      <div class="bg_img" :style="head_bg">

                      </div>
                  </div>
              </div>
              <div class="guanggao_box">
                  <div class="item">
                      <h3>热销专区</h3>
                      <p>舌尖上的美食</p>
                      <!-- <a href="javascript:;">立即抢购&nbsp;></a> -->
                      <div class="item_img_bg1" :style="item_img_bg1">

                      </div>
                  </div>
                  <div class="item">
                      <h3>人气下午茶</h3>
                      <p>茶点5折享</p>
                      <!-- <a href="javascript:;">立即抢购&nbsp;></a> -->
                      <div class="item_img_bg2" :style="item_img_bg2">

                      </div>
                  </div>
              </div>
                      <h1 class="nearby">附近的店铺</h1>
                    <div class="shop_list_box border-bottom-1px" v-if="store_list.length > 0" v-for="(item,i) in store_list" :key="item.id">
                        <div class="shop_list_item">
                            <router-link class="left_fl" tag="div" :to="{ name:'ShopDetails',query:{store_id:item.id,type:'itemFollow'}}">
                                <img :src="item.logo" alt="">
                            </router-link>
                            <div class="right_fl">
                                <div class="right_info">
                                    <router-link tag="div" class="right_info_top" :to="{ name:'ShopDetails',query:{store_id:item.id,type:'itemFollow'}}">
                                        <h3 class="shop_name">{{item.name}}</h3>
                                        <span>{{item.juli}}km</span>
                                    </router-link>
                                    <p class="shop_info">
                                        <!-- {{item.province_name || ""}}
                                        {{item.area_name || ""}} -->
                                        {{item.address || ""}}
                                    </p>
                                    <p v-if="item.kf_mobile" class="shop_info">电话：{{item.kf_mobile}}</p>
                                    <div class="coupon_list coupon_txt"
                                    v-for="(coupon_list,index) in item.coupon_list"
                                    @click="receiveCoupon(coupon_list.id,coupon_list.store_id)">
                                        <div class="coupon_list_left">
                                            <div class="coupon_list_bg" :style="coupon_list_bg">
                                                <p><i class="coupon_icon" :style="coupon_icon"></i>
                                                {{coupon_list.name}}</p>
                                            </div>
                                        </div>
                                        <div class="coupon_list_right" :class="coupon_list.isActive ? 'coupon_action':'coupon_none'">
                                            立即领取
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
        </cube-scroll>
      </div>
      <!-- 获取foot的高度 -->
      <div ref="bottom_h" class="" style="height:1.96rem;position: fixed;bottom: 0;left: 0;">

      </div>
      <tabbar v-show="$route.meta.navShow" :idx="0"></tabbar>
  </div>
</template>
<script>
import tabbar from '@/components/Tabbar'
import wx from 'weixin-js-sdk';
import {Throttle,Debounce} from '@/util/date.js';
export default {
    data(){
        return{
            dinwei_icon:{
                backgroundImage: "url(" + require("../assets/index_position@2x.png") + ")",
                backgroundRepeat: "no-repeat",
                backgroundSize: "cover"
            },
            index_bg:{
                backgroundImage: "url(" + require("../assets/index_bg@2x.png") + ")",
                backgroundRepeat: "no-repeat",
                backgroundSize: "cover"
            },
            down_icon:{
                backgroundImage: "url(" + require("../assets/index_xl@2x.png") + ")",
                backgroundRepeat: "no-repeat",
                backgroundSize: "cover"
            },
            search_icon:{
                backgroundImage: "url(" + require("../assets/index_search@2x.png") + ")",
                backgroundRepeat: "no-repeat",
                backgroundSize: "cover"
            },
            head_bg:{
                backgroundImage: "url(" + require("../assets/index_banner@2x.png") + ")",
                backgroundRepeat: "no-repeat",
                backgroundSize: "cover"
            },
            item_img_bg1:{
                backgroundImage: "url(" + require("../assets/index_cp01@2x.png") + ")",
                backgroundRepeat: "no-repeat",
                backgroundSize: "cover"
            },
            item_img_bg2:{
                backgroundImage: "url(" + require("../assets/index_cp02@2x.png") + ")",
                backgroundRepeat: "no-repeat",
                backgroundSize: "cover"
            },
            coupon_icon:{
                backgroundImage: "url(" + require("../assets/coupon_icon1@2x.png") + ")",
                backgroundRepeat: "no-repeat",
                backgroundSize: "cover"
            },
            coupon_list_bg:{
                backgroundImage: "url(" + require("../assets/coupon_list_bg@2x.png") + ")",
                backgroundRepeat: "no-repeat",
                backgroundSize: "cover"
            },
            search_input:{
                value: "",
                placeholder: '搜索商家名称获得优惠券',
                type: 'text',
                readonly: false,
                maxlength: 100,
                disabled: false,
                autofocus: false,
                autocomplete: false,
                // eye: {
                //     open: true,
                //     reverse: false
                // },
                clearable:{
                    visible: true,
                    blurHidden: true
                }
            },
            options_cate:{
                click:false
            },
            cate_list: [
                {
                    id: "0",
                    name: "推荐"
                }
            ],
            cate_list_action:0,
            getWindowHeight:"",//网页减去foot的高度
          store_list:[],
          store_page:1,//店铺分页
          pullUpLoad: true,
          pullUpLoadThreshold: 0,
          pullUpLoadMoreTxt: '上拉加载更多',
          pullUpLoadNoMoreTxt: '没有更多数据了喔~',
        }
    },
    metaInfo: {
      title: "零壹坊"
    },
    methods:{
        //获取分类
        get_cate_list(){
            let that = this;
            let url = "/fang/store/get_cate_list";
            that.$axios.get(url)
            .then(function (response) {
                let res = response.data;
                if(res.status == 1){
                    that.cate_list = that.cate_list.concat(res.data);
                    //放在这里为了让行业左右滑动的列表加载完成，不然无法进行滑动
                    //true刚进入首页需要进地址查询页面
                    if(that.$cookies.get('bd09_name')){
                        //存在cookie的话就用查找店铺
                        let bd09_name = that.$cookies.get('bd09_name');
                        that.$store.commit('setLocation',bd09_name);
                        that.$store.state.address_status = bd09_name.address_status
                        that.get_store_list(bd09_name.latitude,bd09_name.longitude)
                    }else{
                        //跳转查找地址
                        that.$router.push({ name: 'SelectAddress'})
                        //查找默认的店铺
                        let latitude = that.$store.state.latitude
                        let longitude = that.$store.state.longitude
                        that.store_page = 1;
                        that.store_list = [];
                        that.get_store_list(latitude,longitude);
                    }
                }
            })
            .catch(function (error) {
                console.log(error);
            });
        },
        //选择行业
        btn_select_cate(index){
            let cate = this.cate_list[index];
            this.cate_list_action = cate.id;
            let latitude = this.$store.state.latitude
            let longitude = this.$store.state.longitude
            this.store_page = 1;
            this.store_list = [];
            this.get_store_list(latitude,longitude);
        },
        search_key(){
            this.search_input.value = this.search_input.value;
            let latitude = this.$store.state.latitude
            let longitude = this.$store.state.longitude
            this.store_page = 1;
            this.store_list = [];
            this.get_store_list(latitude,longitude);
        },
        //查找店铺ID是否有重复
      isStoreInArray: function (arr, value) {
          for (var i = 0; i < arr.length; i++) {
              if (value.id == arr[i].id) {
                  return true;
              }
            }
            return false;
        },
        //店铺列表
        get_store_list:Throttle(function(latitude,longitude){
            let that = this;
            const toastlog = this.$createToast({
                time: 0,
                txt: '加载中...'
              })
              toastlog.show()
            let store_page = that.store_page;
            that.$axios.post("/fang/store/get_store_list?page="+store_page, this.$qs.stringify({
                        lat:latitude,
                        lng:longitude,
                        cate_id:this.cate_list_action,
                        keyword:that.search_input.value
                    })
                )
                .then(function (response) {
                    toastlog.hide();
                      let res = response.data;
                      if(res.status == 1){
                          if(res.data.data.length > 0){
                              for(var i =0;i<res.data.data.length; i++){
                                  if(that.isStoreInArray(that.store_list,res.data.data[i])){
                                      console.log("有重复值");
                                  }else{
                                      that.store_list.push(res.data.data[i]);
                                  }
                                  for(var j = 0;j<res.data.data[i].coupon_list.length;j++){
                                      res.data.data[i].coupon_list[j].isActive = false;
                                  }
                              }
                              that.store_page = parseInt(res.data.current_page) + 1;
                          }else{
                              // 如果没有新数据
                              that.$refs.scrolls.forceUpdate();
                          }

                      }else{
                          console.log("没有更多数据!");
                      }
                })
                .catch(function (error) {
                    toastlog.hide();
                    console.log(error);
            });
        },1000),
          onPullingUp() {
              let latitude = this.$store.state.latitude
              let longitude = this.$store.state.longitude
              this.get_store_list(latitude,longitude);
            // 更新数据
        },
        //领取优惠券
        receiveCoupon:Debounce(function(coupon_id,store_id){
            let that = this;
            let url = "/fang/store/user_coupon";
            let _token01 = that.$cookies.get("_token01");
            console.log(_token01)
            //后端返回_user_mark，存在证明没有注册手机号码
            let _user_mark = that.$store.state._user_mark;
            console.log(_user_mark,"_user_mark");
            if(_user_mark){
                let content = "需要注册才能领取,去注册";
                that.createDialog(content);
            }else{
                const toast = that.$createToast({
                    time: 5000,
                    txt: ''
                  })
                  toast.show()
                that.$axios.post(url,this.$qs.stringify({
                    coupon_id:coupon_id,
                    access_token:that.$store.state._token01,
                })).then(function(response){
                     toast.hide();
                    let res = response.data;
                    if(res.status == 1){
                        let content = "领取成功，是否立即去使用";
                        that.showBtn(content,store_id,that);
                        that.coupon_isactive(store_id,coupon_id);
                    }
                    else if (res.status == -1) {
                        that.noLogin();
                    }else{
                        let content = res.msg;
                        that.showToastTxtOnly(content);
                    }
                })
                .catch(function(error){
                    toast.hide();
                });
            }

        },500),
        coupon_isactive(store_id,coupon_id){
            var id = this.store_list.findIndex(function (x) {
                return x.id === store_id
            })
            var couponid = this.store_list[id].coupon_list.findIndex(function (x) {
                return x.id === coupon_id
            })
            this.store_list[id].coupon_list[couponid].isActive = true;
        },
        binzeronefun:function(){
            this.$router.push("/binzerone");
        },
        createDialog(content){
            this.$createDialog({
               type: 'confirm',
               icon: 'cubeic-alert',
               title: '提示信息',
               content: content,
               confirmBtn: {
                 text: '确定',
                 active: true,
                 disabled: false,
                 href: 'javascript:;'
               },
               cancelBtn: {
                 text: '取消',
                 active: false,
                 disabled: false,
                 href: 'javascript:;'
               },
               onConfirm: () => {
                   this.binzeronefun()
               },
               onCancel: () => {

               }
             }).show()
        },
        //使用优惠券
        useCoupon:function(store_id){
            let url = '';
            if(/Alipay/.test(window.navigator.userAgent)) {
                url = this.$store.state.host+'/fang/scanpay/ali?store_id='+store_id;
                window.location.href = url;
            }
            else if (/MicroMessenger/.test(window.navigator.userAgent)) {
                url = this.$store.state.host+'/fang/scanpay/wechat?store_id='+store_id;
                window.location.href = url;
            } else {
                console.log('请使用微信或支付宝支付');
            }

        },
        showBtn(content,store_id,that) {
         this.$createDialog({
           type: 'confirm',
           icon: 'cubeic-alert',
           title: '提示信息',
           content: content,
           confirmBtn: {
             text: '立即使用',
             active: true,
             disabled: false,
             href: 'javascript:;'
           },
           cancelBtn: {
             text: '我再看看',
             active: false,
             disabled: false,
             href: 'javascript:;'
           },
           onConfirm: () => {
             that.useCoupon(store_id);
           },
           onCancel: () => {
           }
         }).show()
         },
         showToastTxtOnly(text) {
          this.toast = this.$createToast({
            txt: text,
            type: 'txt'
          })
          this.toast.show()
        },

    },
    components:{
        tabbar
    },
    computed: {
       options() {
         return {
             pullUpLoad: this.pullUpLoadObj,
             scrollbar: false,
             click:true
         }
       },
      //上拉配置
      pullUpLoadObj: function() {
          return this.pullUpLoad ? {
            threshold: parseInt(this.pullUpLoadThreshold),
            txt: {
              more: this.pullUpLoadMoreTxt,
              noMore: this.pullUpLoadNoMoreTxt
            }
          } : false
        }
    },
    mounted:function(){
        let that = this;
        document.getElementsByTagName("body")[0].className="index_active_bg";
        this.get_cate_list();
        //获取减去底部导航栏的高度
        let getWindowHeight = (document.documentElement.clientHeight || document.body.clientHeight) - this.$refs.bottom_h.offsetHeight;
        this.getWindowHeight = getWindowHeight;
    },
    created() {
        let that = this;

        // this.$nextTick(function () {
            //防止过去不到数据的情况
            // if(that.store_list.length === 0){
            //     setTimeout(function(){
            //         if(that.store_list.length === 0){
            //             let latitude = that.$store.state.latitude;
            //             let longitude = that.$store.state.longitude;
            //             that.store_page = 1;
            //             that.store_list = [];
            //             that.get_store_list(latitude,longitude);
            //         }
            //     },5000);
            // }

        // })
     },
    beforeCreate:function(){
        let that = this;
        document.getElementsByTagName("body")[0].className="index_active_bg";
    },
    activated:function(){
        let that = this;
        console.log("activated")
        //选择地址从author带的参数
        if(this.$route.params.latitude && this.$route.params.longitude){
            that.store_page = 1;
            that.store_list = [];
            this.get_store_list(this.$route.params.latitude,this.$route.params.longitude);
        }
        //使用keep-alive以后进入页面只会触发activated
        document.getElementsByTagName("body")[0].className="index_active_bg";
    },
    beforeDestroy: function() {
        document.body.removeAttribute("class","index_active_bg");
    },
    deactivated:function(){
        //deactivated使用keep-alive以后推出页面只会触发deactivated
        document.body.removeAttribute("class","index_active_bg");
    }
}
</script>
<style scoped>
.index_body{
    height: 100%;
}
.head{
    height: 9.08rem;
    background: #FFFFFF;
}
.head .address{
    height: 1.8rem;
    /* background: linear-gradient(270deg,rgba(26,185,163,1),rgba(31,223,160,1)); */
    display: flex;
    justify-content: center;
    align-items: center;
}
.head .address .address_txt{
    font-size: .64rem;
    color: #FFFFFF;
    font-weight: 500;
}
.head .address .address_txt .dinwei_icon{
    display: inline-block;
    width: .6rem;
    height: .7rem;
    vertical-align: middle;
    margin-right: .4rem;
}
.head .address .address_txt .down_icon{
    display: inline-block;
    width: .44rem;
    height: .24rem;
    vertical-align: middle;
    margin-left: .4rem;
}
.head .nav{
    height: 1.8rem;
    display: flex;
    justify-content: center;
    align-items: center;
    /* background: linear-gradient(270deg,rgba(26,185,163,1),rgba(31,223,160,1)); */
    padding: 0 0 0 .96rem;
    overflow: hidden;
    white-space: nowrap
}
.head .nav ul{
    font-size: 0;
    text-align: left;
}
.head .nav ul li{
    display: inline-block;
    font-size: .6rem;
    color: #FFFFFF;
    font-weight: 500;
    margin-right: .92rem;
    position: relative;
}
.head .nav ul .action{
    font-size: .76rem;
    font-weight: bold;
}
.head .nav ul .action::before{
    content: "";
    display: block;
    width: .8rem;
    height: .16rem;
    background: #FFFFFF;
    border-radius: .08rem;
    position: absolute;
    left: 50%;
    bottom: -0.35rem;
    transform: translate(-50%,0);
}
.head .search{
    height: 1.44rem;
    /* background: linear-gradient(270deg,rgba(26,185,163,1),rgba(31,223,160,1)); */
    overflow: hidden;
}
.head .search .search_input{
    width: 14.16rem;
    height: 1.44rem;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 0 auto;
    background: #FFFFFF;
    border-radius: .72rem;
    z-index: 2;
    position: relative;
    overflow: hidden;
    text-align: center;
}
.head .search .search_input .search_icon{
    display: inline-block;
    width: .52rem;
    height: .52rem;
    margin-right: .22rem;
}
.head .search .search_input p{
    font-size: .56rem;
    color: #909090;
    font-weight: 500;
}
.head .head_bg{
    height: 4.3rem;
    position: relative;
}
.head .head_bg .bg_top{
    height: 3.3rem;
    border-bottom-left-radius: 90%;
    border-bottom-right-radius: 90%;
}
.head .head_bg .bg_img{
    width: 100%;
    height: 4.6rem;
    position: absolute;
    left: 0;
    bottom: 0;
    z-index: 1;
}
.guanggao_box{
    margin:  0;
    padding:1.48rem .24rem 1.48rem .44rem;
    background: #FFFFFF;
    display: flex;
    justify-content: center;
    align-items: center;
}
.guanggao_box .item{
    flex: 1;
    background: #FBFBFB;
    height: 3.88rem;
    margin-right: .2rem;
    padding: 1.3rem .4rem;
    text-align: left;
    position: relative;
    box-sizing: border-box;
}
.guanggao_box .item h3{
    font-size: .72rem;
    color: #333333;
    font-weight: bold;
    margin-bottom: .22rem;
}
.guanggao_box .item p{
    font-size: .48rem;
    color: #777877;
    font-weight: bold;
    margin-bottom: .96rem;
}
.guanggao_box .item a{
    font-size: .4rem;
    color: #F58792;
    font-weight: bold;
}
.guanggao_box .item .item_img_bg1{
    width: 2.92rem;
    height: 2.04rem;
    position: absolute;
    right: .56rem;
    bottom: .56rem;
}
.guanggao_box .item .item_img_bg2{
    width: 2.76rem;
    height: 2.4rem;
    position: absolute;
    right: .56rem;
    bottom: .56rem;
}
.nearby{
    font-size: .8rem;
    color: #333333;
    text-align: left;
    font-weight: bold;
    margin-left: .42rem;
    margin-bottom: .36rem;
    background: #FFFFFF;
}
.shop_list_box{
    margin: 0 0 0 .48rem;
    padding: .52rem .48rem .52rem 0;
    background: #ffffff;
}
.border-bottom-1px::after{
    border-bottom-color: #FFD6D6D6;
}
.shop_list_box .shop_list_item{
        display: flex;
}
.shop_list_box .shop_list_item > .left_fl{
    width: 4.46rem;
    height: 4.16rem;
    flex: none;
    background: #f5f5f5;
}
.shop_list_box .shop_list_item > .left_fl img{
    width: 100%;
    height: 100%;
    object-fit: cover;
}
.shop_list_box .shop_list_item > .right_fl{
    flex: 1;
    display: flex;
    padding-left: .64rem;
    overflow: hidden;
}
.shop_list_box .shop_list_item > .right_fl .right_info{
    overflow: hidden;
    width: 100%;
}
.shop_list_box .shop_list_item > .right_fl .right_info_top{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: flex-end;
}
.shop_list_box .shop_list_item > .right_fl .right_info_top .shop_name{
    font-size:.64rem;
    font-weight:600;
    color:rgba(4,4,4,1);
    overflow: hidden;
    text-overflow:ellipsis;
    white-space: nowrap;
    margin-top: .18rem;
    text-align: left;
}
.shop_list_box .shop_list_item > .right_fl .right_info_top>span{
    font-size:.44rem;
    font-weight:500;
    color:rgba(124,124,124,1);
}
.shop_list_box .shop_list_item > .right_fl .shop_info{
    font-size:.44rem;
    font-weight:500;
    color:rgba(124,124,124,1);
    text-align: left;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
    margin-top: .38rem;
}
.shop_list_box .shop_list_item > .right_fl .coupon_list{
    text-align: left;
    margin-top: .44rem;
        overflow: hidden;
    text-overflow:ellipsis;
    white-space: nowrap;
}
.shop_list_box .shop_list_item > .right_fl .coupon_list .coupon_list_bg{
    width: 5.48rem;
    height: .88rem;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 0 0 0.4rem;
    box-sizing: border-box;
}
.shop_list_box .shop_list_item > .right_fl .coupon_list .coupon_list_bg p{
    overflow: hidden;
    /* text-overflow: ellipsis;
    white-space: nowrap; */
}
.shop_list_box .shop_list_item > .right_fl .coupon_list .coupon_list_bg .coupon_icon{
    display: inline-block;
    width: .44rem;
    height: .44rem;
    vertical-align: middle;
    margin-right: .16rem;
    overflow: hidden;
    text-overflow:ellipsis;
    white-space: nowrap;
}
.shop_list_box .shop_list_item > .right_fl .coupon_list .coupon_list_left{
    float: left;
}
.shop_list_box .shop_list_item > .right_fl .coupon_list .coupon_list_right{
    width: 2.3rem;
    height: .88rem;
    float: left;
    font-size:.44rem;
    font-weight:600;
    color:rgba(255,255,255,1);
    text-align: center;
    line-height: 1rem;
}
.shop_list_box .shop_list_item > .right_fl .coupon_list .coupon_none{
    background:linear-gradient(153deg,rgba(255,196,56,1),rgba(255,208,95,1));
}
.shop_list_box .shop_list_item > .right_fl .coupon_list .coupon_action{
    background:rgba(236,236,236,1);
}
.shop_list_box .shop_list_item > .right_fl .coupon_list  .received{
    background:rgb(246, 246, 246);
}
.shop_list_box .shop_list_item > .right_fl .coupon_txt{
    font-size:.4rem;
    font-weight:500;
    color:rgba(124,124,124,1);
}
.follow_list .cube-scroll-content{
    display: inline-block
}
.nav .cube-scroll-content{
    display: inline-block
}
</style>
<style lang="stylus" rel="stylesheet/stylus">
.cube-scroll-content
    display: block
.follow_list
  .cube-scroll-content
    display: inline-block
.nav
  .cube-scroll-content
    display: inline-block !important
.search_input
    .cube-input-field
        text-align: center;
</style>
